package com.dataeco.api.service.impl;

import com.dataeco.api.entity.Roles;
import com.dataeco.api.entity.UsersRoles;
import com.dataeco.api.entity.User;
import com.dataeco.api.repository.RolesRepository;
import com.dataeco.api.repository.UsersRolesRepository;
import com.dataeco.api.repository.UserRepository;
import com.dataeco.api.service.DataecoUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
public class DataecoUserRoleServiceImpl extends BaseServiceImpl implements DataecoUserRoleService {

    private final UsersRolesRepository dataecoUserRoleRepository;
    private final UserRepository userRepository;
    private final RolesRepository dataecoRoleRepository;

    @Autowired
    public DataecoUserRoleServiceImpl(UsersRolesRepository dataecoUserRoleRepository, UserRepository userRepository, RolesRepository dataecoRoleRepository){
        this.dataecoUserRoleRepository = dataecoUserRoleRepository;
        this.userRepository=userRepository;
        this.dataecoRoleRepository = dataecoRoleRepository;
    }

    @Override
    public List<UsersRoles> findByUserId(String userId) {
        return this.dataecoUserRoleRepository.findByUserId(userId);
    }


    @Override
    public UsersRoles addUserRole(String userId, String roleId) {
        UsersRoles dataecoUserRole =new UsersRoles();
        User user=this.userRepository.findOne(userId);
        Roles dataecoRole =this.dataecoRoleRepository.findOne(roleId);
        if (Objects.isNull(user)||Objects.isNull(dataecoRole)){
            return null;
        }
        dataecoUserRole.getUserRoleKey().setUser(user);
        dataecoUserRole.getUserRoleKey().setDataecoRole(dataecoRole);
        return this.dataecoUserRoleRepository.save(dataecoUserRole);
    }
}
